import React, { Component } from "react";
import axios from "axios";
import PubSub from "pubsub-js";

export default class Search extends Component {
    search = () => {
        // 连续解构赋值+重命名，最终只定义了keyword变量
        const {
            keywordElement: { value: keyword },
        } = this;

        if (keyword.trim().length === 0) {
            alert("请输入待搜索的用户名！");
            return;
        }

        PubSub.publish("updateList", { isFirst: false, isLoading: true });

        axios
            .get("https://api.github.com/search/users?q=" + keyword.trim())
            .then(
                (response) => {
                    // const newTotalUser = response.data.total_count;

                    const newUsers = response.data.items.map((u) => {
                        return {
                            id: u.id,
                            avatarUrl: u.avatar_url,
                            username: u.login,
                            url: u.html_url,
                        };
                    });

                    PubSub.publish("updateList", { users: newUsers });
                },
                (error) => {
                    PubSub.publish("updateList", { err: error });
                    console.error(error);
                }
            )
            .finally(() => {
                PubSub.publish("updateList", { isLoading: false });
            });
    };

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">搜索Github用户</h3>
                <div>
                    <input
                        ref={(c) => (this.keywordElement = c)}
                        type="text"
                        placeholder="输入关键词点击搜索"
                    />
                    &nbsp;<button onClick={this.search}>搜索</button>
                </div>
            </section>
        );
    }
}
